package com.xxg.imagemanager.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * jwt 工具类
 *
 * @author xxg
 * @date 2020-09-26
 */
public class JwtUtils {

    public static final String SECRET = "dLrS-715_dLjZ";

    /**
     * 创建token令牌
     *
     * @param account   用户账号
     * @param timestamp 时间戳
     * @param secret    秘钥
     * @return 令牌
     * @throws JWTCreationException 令牌生成异常
     */
    public static String createJwtToken(String account, String timestamp, String secret) throws JWTCreationException {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withIssuer(account)
                .withClaim("timestamp", timestamp)
                .sign(algorithm);
    }

    /**
     * 验证令牌
     *
     * @param token  令牌
     * @param secret 秘钥
     * @return 令牌信息
     * @throws JWTVerificationException 令牌验证异常
     */
    public static DecodedJWT verifyJwtToken(String token, String secret) throws JWTVerificationException {
        String account = JWT.decode(token).getIssuer();
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(account)
                .build(); //Reusable verifier instance
        return verifier.verify(token);
    }
}
